#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>

#define N 32

#define ERRLOG(errmsg) do{\
															perror(errmsg);\
															printf("file:%s,func:%s,line:%d\n",__FILE__,__func__,__LINE__);\
															exit(-1);\
															}while(0);


int main(int argc, const char *argv[])
{
	if(argc!=3){
		fprintf(stderr,"argc is few of three\n");
		exit(-1);
	}
	int sockfd=-1;
	struct sockaddr_in servaddr;
	socklen_t len=sizeof(servaddr);
	
	if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
		ERRLOG("socker error");
	}

	memset(&servaddr,0,len);
	servaddr.sin_family=AF_INET,
	servaddr.sin_port=htons(atoi(argv[1]));
	servaddr.sin_addr.s_addr=inet_addr(argv[2]);

	if(connect(sockfd,(struct sockaddr*)&servaddr,len)==-1){
		ERRLOG("connect error");
	}

	int fd=-1;
	char filename[N]={0};
	char buf[N]={0};
	ssize_t recvbytes;

	while(1){
		printf("请输入要下载文件名:");
		fgets(filename,N,stdin);
		filename[strlen(filename)-1]='\0';

		if(send(sockfd,filename,N,0)==-1){
			ERRLOG("recv error");
		}

		if(recv(sockfd,buf,N,0)==-1){
			ERRLOG("recv error");
		}

		if(strcmp(buf,"NOEXITS")==0){
			printf("file:%s 不存在\n",filename);
			continue;
		}

		memset(buf,0,N);

		if((fd=open(filename,O_RDWR|O_TRUNC|O_CREAT,0664))==-1){
			ERRLOG("open error");
		}

		while((recvbytes=recv(sockfd,buf,N,0))!=-1){
			if((strcmp(buf,"SUCCESS"))==0){
				break;
			}
			write(fd,buf,recvbytes);
		}
		printf("文件接受完毕\n");
		close(fd);
	}
	
	return 0;
}
